package cc.linker.steplink.crm.merchanth5.controller;

import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.oss.OssService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.SurvivalPushService;
import cc.linker.steplink.crm.merchanth5.service.WxShareService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wxshare")
@Slf4j
public class WxShareController {

    @Autowired
    private MallBoomService mallBoomService;

    @Autowired
    private HttpService httpService;

    @Autowired
    private OssService ossService;

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private PurchaseProcessDao purchaseProcessDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MallDao mallDao;

    @Autowired
    private WxShareService wxShareService;

    @Autowired
    private SurvivalPushService survivalPushService;

    @Autowired
    private RequestFilter requestFilter;

    @Value("${system.scrm.wxpushurl}")
    private String wxpushurl;


    /**
     * 对外接口-生成带参数的二维码【PC端】
     */
    @GetMapping("/api/getlimitqrcode")
    public Map getOutLimitQrcode(
            @RequestParam(value = "token", defaultValue = "", required = true) String token,
            @RequestParam(value = "openid", defaultValue = "", required = true) String openid
                               ) throws Exception {
        if(StringUtils.isEmpty(token) || StringUtils.isEmpty(openid)){
            throw GlobalException.build("token和openid都要传");
        }
        Map<String, Object> cparam = new HashMap<>();
        cparam.put("token",token);
        cparam.put("openId",openid);
        String pCustomerId = purchaseProcessDao.getCustomerIdByTokenAndOpenid(cparam);
        if(StringUtils.isEmpty(pCustomerId)){
            throw GlobalException.build("steplink中无该用户");
        }
        String action = "getLimitQrcode";
        Map<String, String> param = new HashMap<>();
        param.put("token", token);
        param.put("action", action);
        param.put("val", pCustomerId);
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String result = httpService.doPost(wxpushurl, jsonObject.toJSONString());
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if (200 == (Integer) ret.get("errcode")) {
            Map tmpMap = (Map) ret.get("data");
            Map<String, String> res = new HashMap<>();
            res.put("qrcodeurl", ossService.uploadFileToOssByUrl(tmpMap.get("qrcodeurl").toString()));
            return res;
        }
        throw GlobalException.build(ret.get("msg").toString());
    }

    /**
     * 获取带参数的二维码或公众号二维码
     *
     * @param request
     * @return
     * @throws IOException
     * @throws URISyntaxException
     * @throws GlobalException
     */
    @GetMapping("/getlimitqrcode")
    public Map getLimitQrcode(@RequestParam(value = "pCustomerId", defaultValue = "", required = false) String pCustomerId, HttpServletRequest request) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String token = this.mallBoomDao.getTokenByCustomerId(wxUser.getCustomerId());
        if(StringUtils.isEmpty(token)){
            GlobalException.build("未找到公众号信息");
        }
        return this.getLimitQrcodeInfo(token, pCustomerId);
    }

    /**
    * @Description：获取二维码
    * @DateTime：2020/12/30 23:15
    * @Params：
    * @Return：
    */
    public Map getLimitQrcodeInfo(String token,String pCustomerId) throws Exception {
        if ("".equals(pCustomerId)) {
            Map<String, String> retMap = new HashMap<>();
            retMap.put("qrcodeurl", ossService.uploadFileToOssByUrl("https://open.weixin.qq.com/qr/code?username=" + token));
            return retMap;
        }
        String action = "getLimitQrcode";
        Map<String, String> param = new HashMap<>();
        param.put("token", token);
        param.put("action", action);
        param.put("val", pCustomerId);
        LOGGER.info("getLimitQrcodeInfo--------"+JSONArray.toJSON(param));
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String result = httpService.doPost(wxpushurl, jsonObject.toJSONString());
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if (200 == (Integer) ret.get("errcode")) {
            Map tmpMap = (Map) ret.get("data");
            Map<String, String> res = new HashMap<>();
            res.put("qrcodeurl", ossService.uploadFileToOssByUrl(tmpMap.get("qrcodeurl").toString()));
            return res;
        }
        throw GlobalException.build(ret.get("msg").toString());
    }

    /**
     * 写入智能促活用户行为
     */
    @PostMapping("/addcactivelog")
    public void  addcactivelog(@RequestBody Map<String, Object> params){

        if(StringUtils.isEmpty(params.get("customerId"))){
            return;
        }
        if("onlineTest".equals(params.get("action")) || "offlineTest".equals(params.get("action"))
                || "onlineFinish".equals(params.get("action")) || "offlineFinish".equals(params.get("action"))){
            Map<String,Object> customerInfo = wxShareService.getCustomerBaseInfo(params.get("customerId").toString());
            if(null!=customerInfo){
                params.put("openId",customerInfo.get("openId"));
                params.put("token",customerInfo.get("token"));
                params.put("orgId",customerInfo.get("orgId"));
                params.put("lastInteractionTime",null);
                wxShareService.addcactivelog(params);
                String logId = params.get("logId").toString();
                String orgId = params.get("orgId").toString();
                String customerId = params.get("customerId").toString();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String actionTime = sdf.format(new Date());
                survivalPushService.setPushSurvival(customerId,logId,params.get("action").toString(),actionTime,null,orgId,null,null);
            }else{
                throw GlobalException.build("用户不存在");
            }
        }else{
            throw GlobalException.build("参数错误");
        }
    }

    /**
     * 接收微信矩阵推送的关注事件
     *
     * @param token    关注的公众号token
     * @param openid   用户的openid
     * @param eventkey 分享者的customerId
     */
    @PostMapping("/saveshare")
    public void saveShare(@RequestBody Map<String, String> params) {
        if (!params.containsKey("token") || !params.containsKey("openid") || !params.containsKey("eventkey")) {
            return;
        }
        // eventkey是客户的customerId【SELECT CUSTOMER_ID FROM t_crm_busi_customer WHERE CUSTOMER_ID = #{customerId}】
        String pid = params.get("eventkey");
        // 查询当前用户是否存在
        String pCid = mallBoomDao.getCustomerByPrimaryKey(pid);
        // 非本系统用户
        if (StringUtils.isEmpty(pCid)) {
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("token", params.get("token"));
        map.put("openid", params.get("openid"));
        map.put("eventkey", params.get("eventkey"));
        String shareList = "wxsharelist";
        stringRedisTemplate.opsForSet().add(shareList, JSON.serialize(map));
    }


    /**
     * 获取我的客户列表
     *
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getshareuserlist")
    public Object getShareUserList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                   @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                   HttpServletRequest request) {

        PageHelper.startPage(pageIndex, pageSize);

        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        Map<String, Object> payparam = new HashMap<String, Object>();
        payparam.put("orgId",orgId);
//        Integer payModeByOrgId = mallDao.getPayModeByOrgId(payparam);

        Map<String, String> param = new HashMap<String, String>();
        param.put("orgId", orgId);
        param.put("pCustomerId", customerId);
        List<Map<String, String>> shareUserList = mallBoomService.getShareUserList(param);
        if (null != shareUserList) {
            for (Map<String, String> item : shareUserList) {
//                item.put("ifzj",payModeByOrgId.toString());
                item.put("noName","0");
                //  如果用户名称为空则显示用户名称为手机号4位
                if(StringUtils.isEmpty(item.get("customerName"))){
                    item.put("noName","1");
                    if(!StringUtils.isEmpty(item.get("phone"))){
                        String customerPhone = item.get("phone");
                        item.put("customerName","手机尾号"+customerPhone.substring(customerPhone.length()-4)+"用户");
                    }
                }
                item.put("customerId", customerId);
                Long contributionMoney = mallBoomService.getUserContributionMoney(item);
                item.put("contributionMoney", contributionMoney == null ? "0.00" : NumberUtils.fenToYuan(contributionMoney));
                item.remove("phone");
            }
        }
        return new PageInfo<>(shareUserList);
    }


}
